package com.gange.interceptor;

import com.gange.utils.CurUserInfo;
import com.gange.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer userid = (Integer)claims.get("id");
            CurUserInfo.setUserId(userid);
        }catch (Exception e){
            e.printStackTrace();
            //响应错误信息
            response.setContentType("application/json");
            String json = "{\n" +
                    "\t\"code\": 0,\n" +
                    "\t\"msg\": \"NOT_LOGIN\",\n" +
                    "\t\"data\": null\n" +
                    "}";
            response.getWriter().print(json);
            return false;
        }
        //放行请求，returnfasle表示拦截住请求
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //移除ThreadLocal里面的数据
        CurUserInfo.removeUserId();
    }
}
